package com.njlime.member.controller.sys;

import com.njlime.cms.entities.Information;
import com.njlime.cms.entities.TColumn;
import com.njlime.core.base.controller.BaseController;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.helper.GlobalValue;
import com.njlime.core.helper.PageBean;
import com.njlime.core.sdk.wechat.wxpay.MD5Util;
import com.njlime.member.entiies.TField;
import com.njlime.member.entiies.TMember;
import com.njlime.member.service.sys.FieldService;
import com.njlime.member.service.sys.MemberService;
import com.njlime.sys.security.util.UserUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "field")
public class FieldController extends BaseController {

    @Resource
    FieldService fieldService;

    /**
     * 列表
     *
     * @param pageBean
     * @param field
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String list(PageBean pageBean, TField field) {

        logger.info("field/list");
        createXml();
        return toJsonListData(fieldService.list(pageBean, field));
    }

    /**
     * 新增单位时添加数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addAll", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String addAll(PageBean pageBean,int unitId) {
        logger.info("field/addAll");
        Map<String, Object> jsonList = new HashMap<String, Object>();
        try {
            fieldService.addAll(unitId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return toJsonSuccessData();
    }


    /**
     * 編輯状态
     *
     * @param info
     * @param request
     * @return
     */
    @RequestMapping(value = "editStatus", method = RequestMethod.POST)
    @ResponseBody
    public String editStatus(TField info, HttpServletRequest request) {
        logger.info("field/editStatus");
        try {
        if (UserUtils.getUser().getRootUnit() != null) {
                info.setUpdater(UserUtils.getUser().getId());
                info.setUnit_id(UserUtils.getUser().getRootUnit().getId());
                int count = fieldService.updateStatus(info);
                if (count > 0) {
                    return toJsonSuccessData();
                } else {
                    return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "更新失败");
                }
            } else {
                return toJsonErrorData(ExceptionState.MANAGER_EXCEPTION);
            }
        } catch (Exception e) {
            logger.error(e);
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, e.getMessage());
        }

    }

    /**
     * 排序
     *
     * @param id   需要排序的id
     * @param type 1上移 2 下移
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "order")
    public String order(int id, int type) {
        logger.info("field/order");
        try {
            if (UserUtils.getUser().getRootUnit() != null) {
                int count = fieldService.order(id, type, UserUtils.getUser().getRootUnit().getId(), UserUtils.getUser().getId());

                return toJsonSuccessData();
            } else {
                return toJsonErrorData(ExceptionState.MANAGER_EXCEPTION);
            }
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, e.getMessage());
        }

    }


    private String createXml() {
        String xmlString = "";

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            document.setXmlStandalone(true);

            Element itemInfo = document.createElement("PWBRequest");
            document.appendChild(itemInfo);

            Element itemStatistics = document.createElement("transactionName");
            itemStatistics.setTextContent("SEND_CODE_REQ");
            itemInfo.appendChild(itemStatistics);

            Element items = document.createElement("header");
            itemInfo.appendChild(items);

            Element itemName = document.createElement("application");
            itemName.setTextContent("SendCode");
            items.appendChild(itemName);

            Element itemNum = document.createElement("requestTime");
            itemNum.setTextContent("2016-12-20");
            items.appendChild(itemNum);


            Element identityInfo = document.createElement("identityInfo");
            itemInfo.appendChild(identityInfo);

            Element corpCode = document.createElement("corpCode");
            corpCode.setTextContent("SendCode");
            identityInfo.appendChild(corpCode);

            Element userName = document.createElement("userName");
            userName.setTextContent("admin");
            identityInfo.appendChild(userName);


            Element orderRequest = document.createElement("orderRequest");
            itemInfo.appendChild(orderRequest);

            Element order = document.createElement("order");
            orderRequest.appendChild(order);

            Element certificateNo = document.createElement("certificateNo");
            certificateNo.setTextContent("330182198804273139");
            order.appendChild(certificateNo);


            Element linkName = document.createElement("linkName");
            linkName.setTextContent("庄工");
            order.appendChild(linkName);

            Element linkMobile = document.createElement("linkMobile");
            linkMobile.setTextContent("13625814109");
            order.appendChild(linkMobile);

            Element orderCode = document.createElement("orderCode");
            orderCode.setTextContent("t20141204002226");
            order.appendChild(orderCode);

            Element orderPrice = document.createElement("orderPrice");
            orderPrice.setTextContent("200.00");
            order.appendChild(orderPrice);

            Element groupNo = document.createElement("groupNo");
            groupNo.setTextContent("");
            order.appendChild(groupNo);

            Element payMethod = document.createElement("payMethod");
            payMethod.setTextContent("");
            order.appendChild(payMethod);



            Element ticketOrders = document.createElement("ticketOrders");
            order.appendChild(ticketOrders);

            Element ticketOrder = document.createElement("ticketOrder");
            ticketOrders.appendChild(ticketOrder);

            Element childeOrderCode = document.createElement("orderCode");
            childeOrderCode.setTextContent("t2014120400222601");
            ticketOrder.appendChild(childeOrderCode);



            Element credentials = document.createElement("credentials");
            ticketOrder.appendChild(credentials);

            Element credential = document.createElement("credential");
            credentials.appendChild(credential);

            Element name = document.createElement("name");
            name.setTextContent("姓名");
            credential.appendChild(name);

            Element id = document.createElement("id");
            id.setTextContent("身份证");
            credential.appendChild(id);

            Element price = document.createElement("price");
            childeOrderCode.setTextContent("122");
            ticketOrder.appendChild(price);

            Element quantity = document.createElement("quantity");
            quantity.setTextContent("1");
            ticketOrder.appendChild(quantity);

            Element totalPrice = document.createElement("totalPrice");
            totalPrice.setTextContent("1");
            ticketOrder.appendChild(totalPrice);

            Element occDate = document.createElement("occDate");
            totalPrice.setTextContent("2017-1-1");
            ticketOrder.appendChild(occDate);

            Element goodsCode = document.createElement("goodsCode");
            goodsCode.setTextContent("20140331011721");
            ticketOrder.appendChild(goodsCode);

            Element goodsName = document.createElement("goodsName");
            goodsName.setTextContent("商品名");
            ticketOrder.appendChild(goodsName);
            Element remark = document.createElement("remark");
            goodsCode.setTextContent("备注");
            ticketOrder.appendChild(remark);

            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "no");
            DOMSource domSource = new DOMSource(document);

            // xml transform String
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            transformer.transform(domSource, new StreamResult(bos));
            xmlString =  new String(bos.toByteArray(),"UTF-8").split("<PWBRequest>")[1];
            System.out.println(xmlString);
           String md5= MD5Util.MD5Encode(xmlString,"utf-8");
            System.out.println(md5);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return xmlString;
    }
}
